package pers.sports.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.sports.util.UUIDUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 *
 * @datetime 2021/4/21 14:32
 */
@Controller
@RequestMapping("/file")
public class FileController {

    private final static Map map = new HashMap() {{
        put("jpg", "image/jpeg");
        put("jpeg", "image/jpeg");
        put("gif", "image/gif");
        put("png", "image/png");
    }};

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public HashMap UploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        HashMap map = new HashMap();
        if (file.isEmpty()) {
            map.put("code", 1);
            map.put("msg", "文件为空，上传错误");
            map.put("data", "");
            return map;
        }
        //http://localhost:8080/sports/static/tupian.jpg
        String uuid = UUIDUtil.generateShortUuid();
        String fileName = file.getOriginalFilename();
        String[] list1 = fileName.split("\\.");
        if (list1[1] == null || "".equals(list1[1])) {
            map.put("code", 1);
            map.put("msg", "文件名错误，上传错误");
            map.put("data", "");
            return map;
        }
        String newFileName = uuid + '.' + list1[1];
        String filePath = "D:/workspace/files/";
        File dest = new File(filePath + newFileName);
        try {
            file.transferTo(dest);
            HashMap map1 = new HashMap();
            map1.put("src", "http://localhost:8080/sports/file/download?filename=" + newFileName);
            map1.put("title", newFileName);
            map.put("code", 0);
            map.put("msg", "");
            map.put("data", map1);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("code", 1);
        map.put("msg", "文件上传失败");
        map.put("data", "");
        return map;
    }

    @RequestMapping("/download")
    public String downLoad(HttpServletResponse response, @RequestParam("filename") String fileName) throws UnsupportedEncodingException {
        String filePath = "D:/workspace/files/";
        File file = new File(filePath + fileName);
        if (file.exists()) { //判断文件父目录是否存在
            String format = fileName.split("\\.")[1];
            response.setContentType(map.get(format) + ";charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {

                e.printStackTrace();
            }
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
        return null;
    }

}
